package com.xp.basic.heima.nio.netty.simpledemo.chat.handler;

import com.xp.basic.heima.nio.netty.simpledemo.chat.message.ChatRequestMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.message.ChatResponseMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Objects;

/**
 * 如果不加这个注解，客户端直接断开链接
 */
@ChannelHandler.Sharable
public class ChatRequestHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String msgTo = msg.getTo();
        Channel channel = SessionFactory.getSession().getChannel(msgTo);
        //不为空，则在线 channel 未断开
        if (Objects.nonNull(channel)) {
            ctx.writeAndFlush(new ChatResponseMessage(msg.getFrom(),msg.getContent()));
        }else{
            //不在线
            ctx.writeAndFlush(new ChatResponseMessage(msg.getFrom(),"对方用户不在线"));
        }
    }
}
